﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectFitus.Models;
using System.IO;

namespace ProjectFitus.Controllers
{
	[HandleError]
	public class RequestController : Controller
    {

		protected override void OnException(ExceptionContext fc)
		{
			base.OnException(fc);
			FitusLogger.Instance.LogException(fc.Exception);

		}

		IDBFitusRepository m_repo;

        public RequestController()
        {
            m_repo = new DBFitusRepository();
			System.Web.HttpRuntime.Cache["MenuItemsSub"] = m_repo.GetMenuItemsByParentId(4);
        }
        
        // Testing smiður.
		public RequestController(IDBFitusRepository repo)
        {
            m_repo = repo;
        }

         //muna að setja admin í allar userroles
        //Apparently the only variablename the ? operator works with is "id"... But I would have named the variable pageNr
        [Authorize(Roles = "Answers")]
        public ActionResult AdminProjects(int? id)
        {
            if (!id.HasValue)
            {
                //This could be done with id=0; but this method is required for the javascript for the site to function properly
                return RedirectToAction("AdminProjects/"+0, "Request");
            }
                
            IEnumerable<Request> model = m_repo.GetAllRequests();
            ViewData["pageNo"] = id.Value;
            ViewData["ctr"] = "AdminProjects"; 
            ViewData["lastPage"] = "AdminProjects/" + ((id.Value) - 1);
            ViewData["nextPage"] = "AdminProjects/" + ((id.Value) + 1);
            if (User.IsInRole("Answers") && !User.IsInRole("Administrators")) //ef fagaðili með svarréttindi en annars
            {
                model = (from r in model
                            where r.requestType == 2
                            orderby r.dateCreated ascending //elstu fyrst
                            select r);
            }
            if (id.Value == 0)
            {
                ViewData["morePagesToTheLeft"] = "false";
            }
            else
            {
                ViewData["morePagesToTheLeft"] = "true";
            }
            if (model.Skip((id.Value + 1) * 10).Count() == 0)
            {
                ViewData["morePagesToTheRight"] = "false";
            }
            else
            {
                ViewData["morePagesToTheRight"] = "true";
            }
            RequestListAndStatusNamesCapsule into = new RequestListAndStatusNamesCapsule();
            into.requestList = model.Skip(id.Value * 10).Take(10);
            into.statusList = m_repo.GetAllStatusNamesViaSelectListItems();
            return View(into);
        }

        public ActionResult ActiveAdminProjects(int? id)
        {
            if (!id.HasValue)
            {
                //This could be done with id=0; but this method is required for the javascript for the site to function properly
                return RedirectToAction("ActiveAdminProjects/" + 0, "Request");
            }

            IEnumerable<Request> model = m_repo.GetAllRequests().Where((p=> p.statusId == 1 || p.statusId == 2));
            ViewData["pageNo"] = id.Value;
            ViewData["ctr"] = "ActiveAdminProjects";
            ViewData["lastPage"] = "ActiveAdminProjects/" + ((id.Value) - 1);
            ViewData["nextPage"] = "ActiveAdminProjects/" + ((id.Value) + 1);
            if (User.IsInRole("Answers") && !User.IsInRole("Administrators")) //ef fagaðili með svarréttindi en annars
            {
                model = (from r in model
                         where r.requestType == 2
                         orderby r.dateCreated ascending //elstu fyrst
                         select r);
            }
            if (id.Value == 0)
            {
                ViewData["morePagesToTheLeft"] = "false";
            }
            else
            {
                ViewData["morePagesToTheLeft"] = "true";
            }
            if (model.Skip((id.Value + 1) * 10).Count() == 0)
            {
                ViewData["morePagesToTheRight"] = "false";
            }
            else
            {
                ViewData["morePagesToTheRight"] = "true";
            }
            RequestListAndStatusNamesCapsule into = new RequestListAndStatusNamesCapsule();
            into.requestList = model.Skip(id.Value * 10).Take(10);
            into.statusList = m_repo.GetAllStatusNamesViaSelectListItems();
            return View(into);
        }

        public ActionResult UserRequests(int? id)
        {
            if (!id.HasValue)
            {
                //This could be done with id=0; but this method is required for the javascript for the site to function properly
                return RedirectToAction("UserRequests/" + 0, "Request");
            }

            System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
            long userId = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
            IEnumerable<Request> model = m_repo.GetAllRequests().Where(p => p.requestedBy == userId);
            ViewData["pageNo"] = id.Value;
            ViewData["ctr"] = "UserRequests";
            ViewData["lastPage"] = "UserRequests/" + ((id.Value) - 1);
            ViewData["nextPage"] = "UserRequests/" + ((id.Value) + 1);
 
            if (id.Value == 0)
            {
                ViewData["morePagesToTheLeft"] = "false";
            }
            else
            {
                ViewData["morePagesToTheLeft"] = "true";
            }
            if (model.Skip((id.Value + 1) * 10).Count() == 0)
            {
                ViewData["morePagesToTheRight"] = "false";
            }
            else
            {
                ViewData["morePagesToTheRight"] = "true";
            }
            RequestListAndStatusNamesCapsule into = new RequestListAndStatusNamesCapsule();
            into.requestList =  model.Skip(id.Value * 10).Take(10);
            return View(into);
        }

        public ActionResult Details(int id)
        {

            return View();
        }

		[Authorize]
        public ActionResult CreateQuestion()
        {
            return View();
        } 


        [HttpPost]
		[Authorize]
        public ActionResult CreateQuestion(FormCollection collection)
        {
            try
            {   Request question = new Request();

                System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
                question.requestedBy = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
                question.requestDescription = collection["requestDescription"];
                question.dateCreated = DateTime.Now;
                question.requestTitle = collection["requestTitle"];
                question.statusId = 1;
                question.requestType = 2;
                m_repo.CreateRequest(question);

                return View("QuestionSent");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Edit(int id)
        {
            Request request = m_repo.GetRequestById(id);

            RequestEditModel jsonReturnable = new RequestEditModel();

            var hlpr = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary(), new StringWriter()), new ViewPage());

            jsonReturnable.InsertIntoModel(request, hlpr);

            return Json(jsonReturnable, JsonRequestBehavior.AllowGet);
        }

        //
        // POST: /Request/Edit/5
        [HttpPost]
        public ActionResult Edit(FormCollection formData)
        {
            try
            {

                System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
                RequestResponse respo = new RequestResponse();
                //Nota frekar tryParse?
                respo.isActive = true;
                respo.requestId = long.Parse(formData["requestIdBeingEdited"]);

                if (!string.IsNullOrWhiteSpace(formData["responseSubmitText"]))
                {
                    respo.responseText = formData["responseSubmitText"];
                    respo.submittedBy = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
                    respo.dateCreated = DateTime.Now;
                    m_repo.AddRequestResponse(respo);
                }

                if (formData.AllKeys.Contains("statusId"))
                {
                    Request req = m_repo.GetRequestById(long.Parse(formData["requestIdBeingEdited"]));
                    req.statusId = int.Parse(formData["statusId"]);
                    m_repo.UpdateRequest(req);
                }
                return RedirectToAction(formData["ctr"], new { id = int.Parse(formData["pageNo"]) }); 
            }
            catch
            {
                return View();
            }
        }

		[Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Request/Delete/5

        [HttpPost]
		[Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

 
    }
}
